package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type GeneratorTableRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["GeneratorTableRepository"] = &GeneratorTableRepository{}
}

func (r *GeneratorTableRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertGeneratorTable 添加系统生成表
func (r *GeneratorTableRepository) InsertGeneratorTable(sysGeneratorTable *models.GeneratorTable) {

	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	now := models.LocalTime(time.Now())
	sysGeneratorTable.CreateTime = &now
	err := db.Create(sysGeneratorTable).Error
	handleRepositoryErr(err, "添加生成表失败")
	err = db.Model(sysGeneratorTable).Association("Columns").Append(sysGeneratorTable.Columns)
	handleRepositoryErr(err, "添加生成表失败")
}

// DeleteGeneratorTable 删除系统生成表
func (r *GeneratorTableRepository) DeleteGeneratorTable(sysGeneratorTableId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)

	err := db.Delete(&models.GeneratorTable{Id: &sysGeneratorTableId}).Error
	handleRepositoryErr(err, "删除生成表失败")
	db.Where("generator_table_id = ?", sysGeneratorTableId).Delete(models.GeneratorColumns{})
	handleRepositoryErr(err, "删除生成表失败")
}

// UpdateGeneratorTable 修改系统生成表
func (r *GeneratorTableRepository) UpdateGeneratorTable(sysGeneratorTable *models.GeneratorTable) {
	now := models.LocalTime(time.Now())
	sysGeneratorTable.UpdateTime = &now

	err := r.Db.Model(sysGeneratorTable).Omit("id", "create_time", "columns").Updates(sysGeneratorTable).Error
	handleRepositoryErr(err, "修改生成表失败")
	err = r.Db.Where("generator_table_id = ?", *sysGeneratorTable.Id).Delete(models.GeneratorColumns{}).Error
	handleRepositoryErr(err, "修改生成表失败")
	err = r.Db.Model(sysGeneratorTable).Association("Columns").Append(sysGeneratorTable.Columns)
	handleRepositoryErr(err, "修改生成表失败")
}

// SelectGeneratorTable 查询系统生成表
func (r *GeneratorTableRepository) SelectGeneratorTable(sysGeneratorTable *models.GeneratorTable, pageNum, pageSize int) ([]models.GeneratorTable, int) {
	var (
		list  []models.GeneratorTable
		total int64
	)
	db := r.Db.Model(&models.GeneratorTable{})

	if sysGeneratorTable.TabName != nil {
		db.Where("table_name like ?", fmt.Sprintf("%%%s%%", *sysGeneratorTable.TabName))
	}
	if sysGeneratorTable.CommentName != nil {
		db.Where("comment_name like ?", fmt.Sprintf("%%%s%%", *sysGeneratorTable.CommentName))
	}
	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectGeneratorTableById 查询生成表通过ID
func (r *GeneratorTableRepository) SelectGeneratorTableById(id int) models.GeneratorTable {
	var sysGeneratorTable models.GeneratorTable
	//并设置排序
	err := r.Db.Preload("Columns", func(db *gorm.DB) *gorm.DB {
		return db.Order("weight asc")
	}).First(&sysGeneratorTable, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return sysGeneratorTable
}
